package org.bsplus.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.bsplus.util.pagination.ResultPage;
import org.dozer.DozerBeanMapper;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.Assert;

public class MappingUtils
{
    private DozerBeanMapper dozerBeanMapper;

    @Resource
    @Required
    public void setDozerBeanMapper(DozerBeanMapper dozerBeanMapper)
    {
        this.dozerBeanMapper = dozerBeanMapper;
    }

    @SuppressWarnings("unchecked")
    public <T> T map(Object o, Class<T> clazz)
    {
        return (T) dozerBeanMapper.map(o, clazz);
    }

    public <T> List<T> map(List<?> objects, Class<T> clazz)
    {
        Assert.notNull(objects, "List of objects must not be null");
        List<T> results = new ArrayList<T>(objects.size());
        for (Object o : objects) {
            T result = map(o, clazz);
            results.add(result);
        }
        return results;
    }

    public <T> Set<T> map(Set<?> objects, Class<T> clazz)
    {
        Assert.notNull(objects, "Set of objects must not be null");
        Set<T> results = new HashSet<T>(objects.size());
        for (Object o : objects) {
            T result = map(o, clazz);
            results.add(result);
        }
        return results;
    }

    public <T> ResultPage<T> map(ResultPage<?> resultPage, Class<T> clazz)
    {
        List<T> mappedResults = map(resultPage.getResults(), clazz);
        return new ResultPage<T>(mappedResults, resultPage.getTotal());
    }
}
